<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class RoleBasedAccessControl extends BaseModel
{
    public $timestamps = false;
    protected $table = 'sys_controller';
    protected $guarded = [];

    public function permissions()
    {
        return $this->hasMany(RolePermission::class, 'controller_id');
    }
    public static function getAccessID()
    {
        return self::where(['model' => _M_, 'controller' => _C_, 'action' => _A_,])->first('id')->id;
    }

    public function scopeRelatedJoin($query)
    {
        $id = $this->escapeSql(get("id"));
        $query->addSelect("{$this->getTable()}.*");
        $query->addSelect(DB::raw("(SELECT COUNT(*) FROM sys_role_permission a LEFT JOIN sys_role b on a.role_id=b.id WHERE a.controller_id ={$this->getTable()}.id and a.role_id={$id}) as permissions"));
        return $query;
    }
    public function scopeSearch($query, &$search)
    {
        $id = $this->escapeSql(get("id"));
        if (isset($search['permissions'])) {
            $query->whereRaw(DB::raw("(SELECT COUNT(*) FROM sys_role_permission a LEFT JOIN sys_role b on a.role_id=b.id WHERE a.controller_id ={$this->getTable()}.id and a.role_id={$id})={$search['permissions']}"));
            unset($search['permissions']);
        }
        if (isset($search['controller'])) {
            $query->where("{$this->getTable()}.controller", "like", "%" . $search['controller'] . "%");
            unset($search['controller']);
        }
        if (isset($search['action'])) {
            $query->where("{$this->getTable()}.action", "like", "%" . $search['action'] . "%");
            unset($search['action']);
        }
        if (isset($search['model'])) {
            $query->where("{$this->getTable()}.model", "like", "%" . $search['model'] . "%");
            unset($search['model']);
        }
        parent::scopeSearch($query, $search);
        return $query;
    }
}
